#include "OpInput.h"
#include "Network.h"
#include "utils/logger.h"

using namespace std;

OpInput::OpInput(const internal::InputOperation& operation) {
	row_size = 0 ;
	
	for (int i = 0; i < operation.type_size(); ++i) {
		types.push_back((Type) operation.type(i));
		
		if(types.back() == INT || types.back() == BOOL) {
			row_size += sizeof(int32_t);
	    } else if(types.back() == DOUBLE) {
			row_size += sizeof(double);
   		} else {
    		assert(false);
		}
	}
	
	rows = new char[BUFFERSIZE] ;
	number_of_producers = network->nodes_count() ;
	
}

int OpInput::doit() {
	if(number_of_producers == 0) {
		return -1 ;
	}
	
	std::size_t data_len = 0;
	char flag;
	char* source = network->read(&data_len, &flag);
	CHECK(flag == GROUP_BY_MID_FLAG || flag == GROUP_BY_END_FLAG, "Expected group by message");
	CHECK(data_len % row_size == 0, "Bad data length");
	CHECK(data_len <= BUFFERSIZE, "Data length too big");
	
	LOG("dostalem: %d", (int) data_len) ;
	memcpy(rows, source, data_len) ;
	delete [] source ;
	
	if(flag == GROUP_BY_END_FLAG) {
		number_of_producers-- ;
	}
	
	return data_len/row_size ;

	/*static int nr = 0 ;
	if(nr==4) return -1 ;
	else {
		nr++ ;
		void *wsk = rows ;
		for(int i=0 ; i<4 ; i++) {
			*((int32_t*) wsk) = 12345+i ;	wsk += 4 ;
			
			*((int32_t*) wsk) = i ;	wsk += 4 ;
			*((int32_t*) wsk) = i%2 ;	wsk += 4 ;
			*((int32_t*) wsk) = i ;	wsk += 4 ;
			
			*((double*) wsk) = (double) i ;		wsk += sizeof(double) ;
			*((int32_t*) wsk) = i ;	wsk += 4 ;
		}
		return 4 ;
	}*/	
	
}
